<template>
    <div class="login-container">
        <el-form v-if="isLogin" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" style="height:350px" autocomplete="on" label-position="left">
            <div class="title-container" style="margin-bottom:10px">
                <img style="width: 110px;height:55px;margin:auto" src="../../../assets/images/logo.png" />
                <h3 class="title" style="margin: 15px 0px 15px 0px ">TDM试验数据管理系统</h3>
            </div>

            <el-form-item prop="username">
                <span class="svg-container">
                    <!--<svg-icon icon-class="user" />-->
                    <img src="assets/svg/user.svg" />
                </span>
                <el-input ref="username"
                          v-model="loginForm.username"
                          placeholder="用户名"
                          name="username"
                          type="text"
                          tabindex="1"
                          autocomplete="on" />
            </el-form-item>

            <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
                <el-form-item prop="password">
                    <span class="svg-container">
                        <!--<svg-icon icon-class="password" />-->
                        <img src="assets/svg/password.svg" />
                    </span>
                    <el-input :key="passwordType"
                              ref="password"
                              v-model="loginForm.password"
                              :type="passwordType"
                              placeholder="密码"
                              name="password"
                              tabindex="2"
                              autocomplete="on"
                              @keyup.native="checkCapslock"
                              @blur="capsTooltip = false"
                              @keyup.enter.native="handleLogin" />
                    <span class="show-pwd" @click="showPwd">
                        <!--<svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />-->
                        <img :src="passwordType === 'password' ? 'assets/svg/eye.svg' : 'assets/svg/eye-open.svg'" />
                    </span>
                </el-form-item>
            </el-tooltip>
            
            <el-button  :loading="loading" type="primary" class="searchButton" style="width:100%;margin-bottom:10px;" @click.native.prevent="handleLogin">登&nbsp;&nbsp;录</el-button>
            <div style="text-align: right; margin: 10px 0px; font-size: 14px;">
                <span>没有账号?</span>
                <el-link type="primary" style="margin: 0px 0px 3px 3px;" @click="starRegister">点此注册</el-link>
            </div>
        </el-form>
        <el-form ref="registerForm" v-if="!isLogin" :model="registerForm" :rules="registerRules" class="login-form" style="height:480px" label-width="75px" hide-required-asterisk autocomplete="on" label-position="right">
            <div class="title-container" style="margin-bottom:10px">
                <img style="width: 110px;height:55px;margin:auto" src="../../../assets/images/logo.png" />
                <h3 class="title" style="margin: 15px 0px 15px 0px ">TDM试验数据管理系统</h3>
            </div>
            <el-form-item prop="userName" label="用户名">
                <el-input ref="userName"
                          v-model="registerForm.userName"
                          placeholder="用户名"
                          name="userName"
                          type="text"
                          tabindex="1"
                          autocomplete="on" />
            </el-form-item>
            <el-form-item prop="realName" label="姓名">
                <el-input ref="realName"
                          v-model="registerForm.realName"
                          placeholder="姓名"
                          name="realName"
                          type="text"
                          tabindex="2"
                          autocomplete="on" />
            </el-form-item>
            <el-form-item prop="password" label="密码">
                <el-input :key="passwordType"
                          ref="rpassword"
                          v-model="registerForm.password"
                          :type="passwordType"
                          placeholder="密码"
                          name="password"
                          tabindex="3"
                          autocomplete="on" />
                <span style=" font-size: 16px; color: #2d3a4b; cursor: pointer; user-select: none;" @click="showRPwd">
                    <img :src="passwordType === 'password' ? 'assets/svg/eye.svg' : 'assets/svg/eye-open.svg'" />
                </span>
            </el-form-item>
            <el-form-item prop="confirmPassword" label="确认密码">
                <el-input :key="confirmPasswordType"
                          ref="confirmPassword"
                          v-model="registerForm.confirmPassword"
                          :type="confirmPasswordType"
                          placeholder="密码"
                          name="confirmPassword"
                          tabindex="4"
                          autocomplete="on" />
            </el-form-item>
            <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:10px;" class="searchButton" @click.native.prevent="handleRegister">注&nbsp;&nbsp;册</el-button>
            <div style="text-align: right; margin: 10px 0px; font-size: 14px;">
                <span>已有账号?</span>
                <el-link style="margin: 0px 0px 3px 3px;" type="primary" @click="isLogin = true">点此登录</el-link>
            </div>
        </el-form>
    </div>
</template>

<script>

export default {
    data() {
        const validateUsername = (rule, value, callback) => {
            if (this.isSafeLogin) {
                callback();
                return;
            }

            if (!value) {
                callback(new Error('请输入用户名'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (this.isSafeLogin) {
                callback();
                return;
            }

            if (!value) {
                callback(new Error('请输入密码'))
            } else {
                callback()
            }
        }
        const validateRealname = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入姓名'))
            } else {
                callback()
            }
        }
        const validateRusername = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入用户名'))
            } else {
                callback()
            }
        }
        const validateRconfirmPassword = (rule, value, callback) => {
            if (!value || value != this.registerForm.password) {
                callback(new Error('两次输入的密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            loginForm: {
                username: '',
                password: '',
            },
            //formRules: {
            //    userName: [{ required: true, message: '请填写用户名' }],
            //    userCode: [{ required: true, message: '请填写工号' }],
            //    realName: [{ required: true, message: '请填写姓名' }],
            //    password: [
            //        { required: true, message: '请填写密码' },
            //        {
            //            pattern: "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8,12}$", message: '密码包含大小写字母和数字的组合，不能使用特殊字符，长度在8-12之间!'
            //        }
            //    ],
            //    birthday: [{ required: true, message: '请选择出生日期' }],
            //},
            loginRules: {
                username: [{ required: true, trigger: 'blur', validator: validateUsername }],
                password: [{ required: true, trigger: 'blur', validator: validatePassword }]
            },
            registerForm: {
                realName: '',
                userName: '',
                password: '',
                confirmPassword: '',
                isEnable: true,
            },
            registerRules: {
                realname: [{ required: true, trigger: 'blur', validator: validateRealname }],
                username: [{ required: true, trigger: 'blur', validator: validateRusername }],
                password: [{ required: true, trigger: 'blur', pattern: /^.{6,}$/, message: '密码长度不少于6位' }],
                confirmPassword: [{ required: true, trigger: 'blur', validator: validateRconfirmPassword }],
            },
            confirmPasswordType: 'password',
            passwordType: 'password',
            capsTooltip: false,
            loading: false,
            showDialog: false,
            redirect: undefined,
            otherQuery: {},

            safeDomain: 'imro8',
            isSafeLogin: false,
            isLogin: true,
        }
    },
    mounted() {
        if (this.loginForm.username === '') {
            this.$refs.username.focus()
        } else if (this.loginForm.password === '') {
            this.$refs.password.focus()
        }

        this.intiSafeLogin();
    },
    methods: {
        intiSafeLogin() {
            if (this.safeDomain == null || this.safeDomain.length == 0) return;
            var query = this.$route.query;
            if (!query[this.safeDomain]) return;
            var params = query[this.safeDomain]
                .split(',')
                .map(e => e.split('='));
            var i = params.findIndex(e => e[0] === ' T');
            if (i < 0 || params[i].length < 2) return;
            this.loginForm.domain = this.safeDomain;
            this.loginForm.username = params[i][1];
            this.loginForm.password = "xxx";
            this.handleLogin();
        },

        checkCapslock(e) {
            const { key } = e;
            this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z');
        },
        starRegister() {
            this.isLogin = false;
            this.registerForm = {
                realName: '',
                userName: '',
                password: '',
                confirmPassword: '',
                isEnable: true,
            }
        },
        showPwd() {
            if (this.passwordType === 'password') {
                this.passwordType = '';
            } else {
                this.passwordType = 'password';
            };
            this.$nextTick(() => {
                this.$refs.password.focus();
            });
        },
        showRPwd() {
            if (this.passwordType === 'password') {
                this.passwordType = '';
            } else {
                this.passwordType = 'password';
            };
            this.$nextTick(() => {
                this.$refs.rpassword.focus();
            });
        },
        handleLogin() {
            //if（!!this.loginForm.username && !!this.loginForm.password）{
            //    this.$notify({ title: this.loginForm.username, message: '登录成功', type: 'success', duration: 1000 });
            //    this.$router.push('/Home');
            //}
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$store.dispatch('login', this.loginForm).then(() => {
                        axios.get(requestURL + '/UserQuery/QueryUsers').then(res => {
                            sessionStorage.setItem('userList', JSON.stringify(res.data));
                            console.log(res, JSON.parse(sessionStorage.getItem('userList')))
                            this.$notify({ title: this.loginForm.username, message: '登录成功', type: 'success', duration: 1000 });
                            this.$router.push('/Home');
                            this.loading = false;
                        }).catch(() => {
                        });
                    }).catch(() => {
                        this.loading = false;
                    });
                } else {
                    return false;
                }
            });
        },
        
        handleRegister() {
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    axios.post(requestURL + "/DaUser/CreateUser", this.registerForm).then(res => {
                        if (res.data.status === 'Success') {
                            this.loading = false;
                            this.loginForm.username = this.registerForm.userName;
                            this.loginForm.password = this.registerForm.password;
                            this.$store.dispatch('login', this.loginForm).then(() => {
                                axios.get(requestURL + '/UserQuery/QueryUsers').then(resf => {
                                    sessionStorage.setItem('userList', JSON.stringify(resf.data));
                                    this.$notify({ title: this.loginForm.username, message: '登录成功', type: 'success', duration: 1000 });
                                    this.$router.push('/Home');
                                    this.loading = false;
                                }).catch(() => {
                                });
                            });
                        } else {
                            this.loading = false;
                            res.data.error ? this.$message({ type: 'warning', message: res.data.error }) : this.$message({ type: 'warning', message: '注册失败!' });
                        }
                    }).catch(err => {
                        this.loading = false;
                        this.$message({ type: 'warning', message: '注册失败!' });
                    })
                } else {
                    return false;
                }
            });
        },
    },
    template: "#template"
}
</script>
